package com.kedacom.freedomLabel.view.activity;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.databinding.ViewDataBinding;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hard.CardReadHelp;
import com.hard.ReturnValue;
import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.BR;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.broadcastreceiver.NetBroadcastReceiver;
import com.kedacom.freedomLabel.databinding.ActivityScaleBinding;
import com.kedacom.freedomLabel.databinding.ItemPluShowBinding;
import com.kedacom.freedomLabel.databinding.ItemRubbishSaveBinding;
import com.kedacom.freedomLabel.initdata.InitCategoryNew;
import com.kedacom.freedomLabel.initdata.bean.CategoryNewBean;
import com.kedacom.freedomLabel.initdata.bean.Classes;
import com.kedacom.freedomLabel.initdata.bean.EventBusMessage;
import com.kedacom.freedomLabel.initdata.bean.Goods;
import com.kedacom.freedomLabel.initdata.bean.ProductDetail;
import com.kedacom.freedomLabel.initdata.bean.RubbishBean;
import com.kedacom.freedomLabel.initdata.bean.Staff;
import com.kedacom.freedomLabel.initdata.bean.Team;
import com.kedacom.freedomLabel.model.SelectType;
import com.kedacom.freedomLabel.model.bean.Config;
import com.kedacom.freedomLabel.model.bean.ConfigKeys;
import com.kedacom.freedomLabel.model.bean.Operator;
import com.kedacom.freedomLabel.model.bean.Product;
import com.kedacom.freedomLabel.model.bean.Template;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.DataLoader;
import com.kedacom.freedomLabel.model.db.dao.ConfigDao;
import com.kedacom.freedomLabel.model.db.dao.ProductDao;
import com.kedacom.freedomLabel.utils.IPUtil;
import com.kedacom.freedomLabel.utils.NumFormatUtil;
import com.kedacom.freedomLabel.utils.SPUtil;
import com.kedacom.freedomLabel.utils.ScanGunKeyEventHelper;
import com.kedacom.freedomLabel.utils.SerialPortSplice;
import com.kedacom.freedomLabel.view.widget.ProductSelectItemView;
import com.kedacom.freedomLabel.viewmodel.ScaleViewModel;
import com.kedacom.lego.adapter.recyclerview.LegoBaseRecyclerViewAdapter;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.OnMessage;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.util.AndroidUtils;
import com.seray.scaleviewlib.utils.LogUtils;
import com.seray.scaleviewlib.utils.ToastUtils;
import com.skyworth.splicing.SerialPortUtil;
import com.tscale.scalelib.jniscale.JNIScale;
import com.vilyever.socketclient.SocketClient;
import com.vilyever.socketclient.helper.SocketClientDelegate;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

import static com.kedacom.freedomLabel.initdata.InitCategoryNew.DeleteCategory;


@ContentView(R.layout.activity_scale)
@ViewModel(ScaleViewModel.class)
public class ScaleActivity extends BaseActivity<ActivityScaleBinding, ScaleViewModel> implements ScanGunKeyEventHelper.OnScanSuccessListener {

    private static final String TODO = "获取设备码出错";
    private View.OnClickListener mProductSelectViewClickListener = view -> {
        ProductSelectItemView selectItemView = (ProductSelectItemView) view;
        String itemCategory = selectItemView.getItemCategory();
        Intent intent = new Intent(ScaleActivity.this, SelectItemActivity.class);
        intent.putExtra(Options.KEY_SELECT_TYPE, SelectType.TYPE_ITEM);
        intent.putExtra(Options.KEY_ITEM_CATEGORY, itemCategory);
        startActivityForResult(intent, 0x11);
    };

    private JNIScale mScale;
    private ScaleHandler mScaleHandler = new ScaleHandler(new WeakReference<>(this));
    private ScheduledExecutorService timerThreads = Executors.newScheduledThreadPool(1);

    private ScheduledExecutorService timerIntervalRecording = Executors.newScheduledThreadPool(1);

    private ScheduledExecutorService timerIntervalSetTTT = Executors.newScheduledThreadPool(1);

    private ScheduledFuture<?> timerIntervaFuture = null;

    private ScheduledFuture<?> timerIntervaFutureSet = null;

    //    private String timerIntervaInit = "0";
//    private String beepsound = "0";
//    private String onlineOfflineRecordData = "0";
//    private int weightStatusStr = 0;
//    private int lastWeightStatus = 100;

    private boolean beepsoundZero = true;
    private boolean beepsoundOne = true;
    private boolean beepsoundTwo = true;
    private boolean beepsoundThr = true;

    private SimpleDateFormat sdf001 = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());

//    private float lowerLimit = -1;
//    private float upperLimit = -1;

    private float lowerLimit = 0.0f;
    private float upperLimit = 0.0f;
    // 选中的产品
    private Product product;
    public String oldProductName;
    public String productOlduuid;
    // 选中的操作员
    private Operator operator;
    private float currentWeight;  // 实际重量
    private float lastWeight = 0.0f;
    private float grossWeight; // 毛重
    private float lastGrossWeight = 0.0f; // 毛重
    private float accumCurrentWeight = 0.0f;  // 累加实际重量
    private float accumGrossWeight = 0.0f; // 累加毛重
    private boolean isAccum = false; // 是否累加

    private float singleWeight = 0.000001f; // 单重,防止除法异常

    private long exitTime = 0;

    private CardReadHelp mReadCardHelp;
    private boolean isStop = false;

    private boolean isScalesSwitchServer = false;
    private boolean isForceRecord = false;
    private boolean isShowPrice = false;
    private boolean isForceRecordStable = false;
    private boolean isLoadAutoRecord = false;
    private boolean isOpenPrint = false;
    private boolean isOpencom = true;

    private int isForceRecordStableInt = 0;
    private float isLoadAutoRecordWeight = 0.0f;

    private boolean isAddWeight = false;

    //    private FileDownLoadUtil fileServer;
    private ConfigDao dao;
    private boolean isKgMode = false; // kg模式
    private boolean isgMode = false;//g模式
    //小数点
    private String scalesDecimalPoint = "%.3f";
    private String scalesDecimalPointText = "0.000";

    private float threshold = 0.1f;


    AlertDialog.Builder builder = null;
    AlertDialog.Builder builder01 = null;
    private ScanGunKeyEventHelper mGunHelper;
    private SerialPortUtil mSerialPortUtil;
    private SerialPortUtil mSerialPortUtilCom;
    //    private PrinterServiceConnection conn = null;
//    private GpService mGpService = null;
    private static final int MAIN_QUERY_PRINTER_STATUS = 0xfe;
    //打印机id 0 ， 0 1 2 都可以  目前唯一0
    private int mPrinterIndex = 0;
    private String devicename = "";
    private int Weighing_serial_number = 1;
    Gson gson = new Gson();
    Template template;

    String[] columnNames = {};
    Boolean[] booleansNames = {};


    private String zxingname = "";
    private SocketClient socketClient;
    public static String socketUrl = "";
    private String oldSocketUrl = "";
    private SocketClientDelegate delegate;

    private String deviceCodeStr = "";

    private SPUtil spUtil;

    private Goods selectGoods = null;
    private Classes selectClass = null;
    private Team selectTeam = null;
    private Staff selectStaff = null;

    private ProductDetail selectProductDetail = null;

    ArrayAdapter<String> machineAdapter;
    List<String> machineList = new ArrayList<>();

    ArrayAdapter<String> modelAdapter;
    List<String> modelList = new ArrayList<>();

    ArrayAdapter<String> smallAdapter;
    List<String> smallList = new ArrayList<>();

    private NetBroadcastReceiver receiver;


    private String BaseNameUrl = "";

    LegoBaseRecyclerViewAdapter<RubbishBean> adapter;
    LegoBaseRecyclerViewAdapter<CategoryNewBean> categoryNewBeanLegoBaseRecyclerViewAdapter;

    List<RubbishBean> rubbishBeanArrayList = new ArrayList<>();
    List<CategoryNewBean> categoryNewBeanArrayList = new ArrayList<>();
    List<RubbishBean> rubbishBeanAddWeight = new ArrayList<>();

    // 选中的产品
    private CategoryNewBean categoryNewBean;


    private String BaseUrl = "https://rub.silingkeji.com/api/rb/site/category";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        addDefaultAttributeSelectView();
        try {
            initScale();
            initViews();

            // 保存开机时间
            saveAppStartTime();
            mGunHelper = new ScanGunKeyEventHelper(this);
            register();

//        registerReceiver(mBroadcastReceiver, new IntentFilter(GpCom.ACTION_DEVICE_REAL_STATUS));




//            mViewModel.weightStatus.observe(this, new Observer<Integer>() {
//                @Override
//                public void onChanged(@Nullable Integer status) {
//
//
//                }
//            });
            spUtil = new SPUtil(ScaleActivity.this, "Scales");


            receiver = new NetBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            registerReceiver(receiver, intentFilter);


        } catch (Exception e) {
            LogUtils.d("onCreate==e=======" + e.toString());
            DialogRestartApp("不要频繁初始化,初始化出错，请重启");
            e.printStackTrace();
        }


    }


    private void saveAppStartTime() {
        try {
            ConfigDao dao = AppDatabase.getInstance().configDao();
            DataLoader.save(dao, new Config("app_start_time", String.valueOf(new Date().getTime())));
        } catch (Exception e) {
            System.out.println("e======pStartTime" + e.toString());
            e.printStackTrace();
        }

    }

    private void initViews() {
        String appVersionName = AndroidUtils.getVersionName(this);
        int appVersionCode = AndroidUtils.getVersionCode(this);
        mBinding.version.setText(String.format("%s_%s", appVersionName, appVersionCode));
        mBinding.timer.setText(NumFormatUtil.getFormatDate());

        mBinding.recycler.setLayoutManager(new LinearLayoutManager(this));
        adapter = new LegoBaseRecyclerViewAdapter<RubbishBean>(R.layout.item_rubbish_save, new ArrayList<>(), BR.business) {
            @Override
            protected void onCustomBindItem(ViewDataBinding binding, int position) {
                super.onCustomBindItem(binding, position);
                ((ItemRubbishSaveBinding) binding).businessIndex.setText(String.valueOf(position + 1));
                ((ItemRubbishSaveBinding) binding).businessName.setTextSize(16);
                ((ItemRubbishSaveBinding) binding).businessNetWeight.setTextSize(16);
                ((ItemRubbishSaveBinding) binding).businessLayout.setBackgroundColor(
                        ContextCompat.getColor(ScaleActivity.this, position % 2 == 0 ? R.color.text_white : R.color.diffter)
                );

                ((ItemRubbishSaveBinding) binding).businessDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        beep();
                        rubbishBeanArrayList.remove(position);
                        showTotalMoney();
                    }
                });
            }
        };
        mBinding.recycler.setAdapter(adapter);


        mBinding.recyclerPlu.setLayoutManager(new GridLayoutManager(this, 3));
        categoryNewBeanLegoBaseRecyclerViewAdapter = new LegoBaseRecyclerViewAdapter<CategoryNewBean>(R.layout.item_plu_show, new ArrayList<>(), BR.category) {
            @Override
            protected void onCustomBindItem(ViewDataBinding binding, final int position) {
                super.onCustomBindItem(binding, position);

                if (position < 5) {
                    ((ItemPluShowBinding) binding).productName.setText(categoryNewBeanArrayList.get(position).name);
                    if(isShowPrice){
                        ((ItemPluShowBinding) binding).productPrice.setVisibility(View.VISIBLE);
                        ((ItemPluShowBinding) binding).productPrice.setText(categoryNewBeanArrayList.get(position).getPrice());
                        ((ItemPluShowBinding) binding).productName.setGravity(Gravity.CENTER|Gravity.BOTTOM);
                    }else {
                        ((ItemPluShowBinding) binding).productPrice.setVisibility(View.GONE);
                        ((ItemPluShowBinding) binding).productName.setGravity(Gravity.CENTER);
                    }
                }

                if (position == 5) {

                    ((ItemPluShowBinding) binding).productName.setText("更多>>");

                }

                ((ItemPluShowBinding) binding).productLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        beep();
                        if (position < 5) {
                            categoryNewBean = categoryNewBeanArrayList.get(position);
                            onCategorySelect();
                        }
                        if (position == 5) {
                            Intent intent = new Intent(ScaleActivity.this, SelectItemActivity.class);
                            intent.putExtra(Options.KEY_SELECT_TYPE, SelectType.TYPE_CATEGORY);
                            startActivityForResult(intent, 0x11);
                        }


                    }
                });
            }
        };

        mBinding.recyclerPlu.setAdapter(categoryNewBeanLegoBaseRecyclerViewAdapter);

        String socketUrl = PreferenceManager.getDefaultSharedPreferences(ScaleActivity.this).getString("scales_post_url_post_base", BaseUrl);

        try {
            dao = AppDatabase.getInstance().configDao();
            List<Config> deviceCode = dao.get(ConfigKeys.DEVICE_CODE);
            if (deviceCode.size() > 0) {
                deviceCodeStr = deviceCode.get(0).configValue;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!TextUtils.isEmpty(deviceCodeStr)) {
            InitCategoryNew.TestInterfaceGetCategory(socketUrl, deviceCodeStr);
        } else {
            showToast("设备码为空,请先去系统设置 -> 基本信息里面里面设置设备编号", TOAST_INFO);
        }


//        mViewModel.inserCategory();
//        ShowPlu();

    }


    private void onCategorySelect() {
        mBinding.categoryNameShow.setText(categoryNewBean.name);
    }

    @OnMessage("RefreshCategory")
    private void getRefreshCategory() {
        ShowPlu();
    }

    private void ShowPlu() {

        List<CategoryNewBean> categoryNewBeans = AppDatabase.getInstance().getCategoryNewDao().get();
        mScaleHandler.post(new Runnable() {
            @Override
            public void run() {
                if (categoryNewBeans != null) {
                    if (categoryNewBeans.size() >= 6) {
                        categoryNewBeanArrayList.clear();
                        categoryNewBeanArrayList = categoryNewBeans.subList(0, 6);
                        categoryNewBeanLegoBaseRecyclerViewAdapter.setData(categoryNewBeanArrayList);
                    } else {
                        categoryNewBeanArrayList.clear();
                        categoryNewBeanArrayList = categoryNewBeans;
                        categoryNewBeanLegoBaseRecyclerViewAdapter.setData(categoryNewBeanArrayList);
                    }

                }

            }
        });


    }


    private void showTotalMoney() {
        BigDecimal addBusinessWeight = new BigDecimal(0);
        if (rubbishBeanArrayList.size() > 0) {
            for (RubbishBean busine : rubbishBeanArrayList) {
                addBusinessWeight = addBusinessWeight.add(new BigDecimal(busine.weight));
            }
            mBinding.weightAllShow.setText(addBusinessWeight + mScale.getStringUnit());
            adapter.setData(rubbishBeanArrayList);
        } else {
            adapter.setData(rubbishBeanArrayList);
            mBinding.weightAllShow.setText("");
        }


    }

//    @OnMessage("getMachineList")
//    private void getMachineListSuccess(List<MachineNumber> machineNumberList) {
//        machineAdapter.clear();
//        List<String> machineNameList = new ArrayList<>();
//        machineNameList.clear();
//        for (MachineNumber machineNumber : machineNumberList) {
//            machineNameList.add(machineNumber.getMachineName());
//        }
//        machineAdapter.add("");
//        machineAdapter.addAll(machineNameList);
//    }

//    public void selectProduct(View view) {
//        beep();
//        if (view.getTag() == null) {
//            Intent intent = new Intent(ScaleActivity.this, SelectItemActivity.class);
//            intent.putExtra(Options.KEY_SELECT_TYPE, SelectType.TYPE_PRODUCT);
//            startActivityForResult(intent, 0x11);
//        } else if (view.getTag() instanceof Product) {
//            product = (Product) view.getTag();
//            onProductSelect();
//        }
//    }

//    private void onProductSelect() {
//        if (isKgMode) {
//            if (product.preTare > 0) {
//                mScale.pretare((float) (product.preTare / 1000));
//            } else {
//                mScale.pretare(0);
//            }
//
//        }
//
//        mBinding.productSelectItemLayout.setItemViewResult(ProductTotalItemLayout.CATEGORY_PRODUCT,
//                product.uuid, product.name, product);
//        if (product.openGroupSetting) {
//            mViewModel.getProductItemInfo(product.groupUUID, product.groupName);
//        }
//    }


    private void register() {
        IntentFilter timeFilter = new IntentFilter();
        timeFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(timeReceiver, timeFilter);
    }


    // 显示总计
    public void showRecord(View view) {
        beep();
//        Intent intent = new Intent(ScaleActivity.this, DataAnalysisActivity.class);
//        startActivity(intent);
        DialogShowRecord();
    }

    // 重新获取数据
    public void getCategory(View view) {
        beep();
        if (deviceCodeStr == null || TextUtils.isEmpty(deviceCodeStr)) {
            showToast("设备码为空，请先去系统设置 -> 基本信息里面里面设置设备编号", TOAST_INFO);
            return;
        }

        againGetData();
    }


    public void DialogShowRecord() {
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.dialog_show_record, null);
        final EditText editTextName = (EditText) textEntryView.findViewById(R.id.editTextName);
        final EditText editTextNumEditText = (EditText) textEntryView.findViewById(R.id.editTextNum);
        AlertDialog.Builder ad1 = new AlertDialog.Builder(ScaleActivity.this);
        ad1.setTitle("进入总计:");
        ad1.setView(textEntryView);
        ad1.setPositiveButton("管理员", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int i) {
                String name = editTextName.getText().toString();
                String pass = editTextNumEditText.getText().toString();
                if (name == null || TextUtils.isEmpty(name)) {
                    showToast("请输入名字", TOAST_WARNING);
                    return;
                }
                if (pass == null || TextUtils.isEmpty(pass)) {
                    showToast("请输入密码", TOAST_WARNING);
                    return;
                }

                if ("admin".equals(name)
                        && pass.equals(PreferenceManager.getDefaultSharedPreferences(ScaleActivity.this).getString("scales_record_password", "000000"))) {
                    spUtil.putString("scales_record_admin", "999999");
                    Intent intent = new Intent(ScaleActivity.this, ScaleRecordActivity.class);
                    startActivity(intent);
                } else {
                    showToast("密码错误", TOAST_ERROR);
                }

            }
        });
        ad1.setNeutralButton("操作员", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                spUtil.putString("scales_record_admin", "888888");
                Intent intent = new Intent(ScaleActivity.this, ScaleRecordActivity.class);
                startActivity(intent);
            }
        });
        ad1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int i) {

            }
        });
        ad1.setCancelable(false);
        ad1.show();// 显示对话框

    }


    // 设置为计数模式
//    public void toCountMode(float sWeight, int samplingCount) {
//
//        // 清除扣重
//        mScale.pretare(0);
//
//        if (sWeight > 0) { // 采样
//            singleWeight = sWeight;
//        } else { // 单重切换
//            singleWeight = grossWeight / samplingCount;  // 使用毛重进行计算，扣重有可能还没有生效
//        }
//
//        // 单重 显示
//        mViewModel.displayPreTare.set(String.format(Locale.getDefault(), scalesDecimalPoint, singleWeight));
//
//        if (mViewModel.isWeightMode.getValue()) { // 称重模式切换到计数模式是 计算上下限
//            lowerLimit = Math.round(lowerLimit / singleWeight);
//            mBinding.productBottomLimit.setText(String.format("%s个", ((int) lowerLimit)));
//
//            upperLimit = Math.round(upperLimit / singleWeight);
//            mBinding.productTopLimit.setText(String.format("%s个", ((int) upperLimit)));
//        }
//
//        mViewModel.isWeightMode.set(false);
//    }

    public void selectRubbish(View view) {
        beep();
        if (view.getTag() == null) {
            Intent intent = new Intent(ScaleActivity.this, SelectItemActivity.class);
            intent.putExtra(Options.KEY_SELECT_TYPE, SelectType.TYPE_CATEGORY);
            startActivityForResult(intent, 0x11);
        }
    }


    public void cleansRubbish(View view) {
        beep();
        categoryNewBean = null;
        mBinding.categoryNameShow.setText("");
    }


    // 保存数据
    public void saveRecord(View view) {
        if (isStable()) {
            saveRecordMethod(currentWeight, grossWeight);
        }


    }

    public void CreateImage(View view) {
        beep();

        String baseUrl = PreferenceManager.getDefaultSharedPreferences(this).getString("scales_post_url_post", BaseNameUrl);

        mViewModel.saveRecord(rubbishBeanArrayList);

        AppExecutors.getInstance().queryIO()
                .submit(() -> {
                    StringBuffer stringBuffer = new StringBuffer();
                    if (rubbishBeanArrayList.size() > 0) {
                        for (RubbishBean rubbishBean : rubbishBeanArrayList) {
                            stringBuffer.append(rubbishBean.toString() + "#");
                        }

                    } else {
                        showToast("没有数据要生成二维码", TOAST_WARNING);
                        return;
                    }


                    String imageUrl = baseUrl + stringBuffer.toString();

                    Bitmap bitmap = QRCodeEncoder.syncEncodeQRCode(imageUrl, BGAQRCodeUtil.dp2px(ScaleActivity.this, 200));
                    mScaleHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mBinding.createImage.setImageBitmap(bitmap);
                            rubbishBeanArrayList.clear();
                            showTotalMoney();
                        }
                    });


                });
    }


    private void saveRecordMethod(float lastCurr, float lastGross) {

        if (isOL()) {
            showToast("当前超量程", TOAST_INFO);
            return;
        }

        if (isForceRecord || isForceRecordStable) {
            if (lastWeight <= 0) {
                showToast("当前重量不能小于等于零", TOAST_INFO);
                return;
            }
        } else {
            if (currentWeight <= 0) {
                showToast("当前重量不能小于等于零", TOAST_INFO);
                return;
            }
        }


        WeightInfo(lastCurr);


    }


    private int showId = 0;

    static SimpleDateFormat formatter01 = new SimpleDateFormat("yyyyMMdd");


    private void WeightInfo(float currentWeight) {

        closeDialog();

        if (isTextNull(mBinding.categoryNameShow)) {
            showToast("请选择垃圾类别", TOAST_INFO);
            return;
        }


        if (isAddWeight) {
            showToast("没有归零,不做记录", TOAST_INFO);
            return;
        }

        RubbishBean rubbishBean = new RubbishBean();
        rubbishBean.category = mBinding.categoryNameShow.getText().toString();
        rubbishBean.weight = currentWeight + "";
        rubbishBean.weighingTime = new Date().getTime();
        rubbishBean.weightUnit = mScale.getStringUnit();
        rubbishBean.category_id = categoryNewBean.getOtherId()+"";
        rubbishBean.price=categoryNewBean.getPrice();

        try {

            //判断放到最后
            if (isForceRecordStable) {
                isForceRecordStableInt = 1;
            }
            if (isLoadAutoRecord) {
                isLoadAutoRecordWeight = currentWeight;
            }

            beep();
            rubbishBeanArrayList.add(rubbishBean);

            isAddWeight = true;

            showTotalMoney();

        } catch (Exception e) {
            showToast("数据封装提交出现错误" + e.toString(), TOAST_ERROR);
        }


    }

    private boolean isTextNull(TextView textView) {
        if (textView.getText() == null || TextUtils.isEmpty(textView.getText().toString())) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isSpinnerNull(Spinner spinner) {
        if (spinner.getSelectedItem() == null || TextUtils.isEmpty(spinner.getSelectedItem().toString())) {
            return true;
        } else {
            return false;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == RESULT_OK) {
            String jsonData = data.getStringExtra(Options.KEY_SELECT_RESULT);
            SelectType dataType = (SelectType) data.getSerializableExtra(Options.KEY_SELECT_TYPE);
            if (dataType == null || TextUtils.isEmpty(jsonData)) return;
            Gson gson = new Gson();

            if (dataType == SelectType.TYPE_CATEGORY) {
                categoryNewBean = gson.fromJson(jsonData, CategoryNewBean.class);
                mBinding.categoryNameShow.setText(categoryNewBean.getName());

            }

        } else if (requestCode == 0x12 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            zxingname = bundle.getString("result");
            checckNameBySccan(zxingname);
//                mBinding.productSelectItemLayout.setItemViewResult(ProductTotalItemLayout.CATEGORY_SCAN,
//                        zxingname, zxingname, null);
        }

    }

    private void initScale() {
        mScale = JNIScale.getScale();
        mScale.setStabDelay(40);
        if (mScale.getUnit() > 1) {
            showToast("该秤只支持克或者千克模式，设置完成后请重新新启动。", TOAST_ERROR);
        }

        if (mScale.getUnit() == 0) {
            isKgMode = true;
            isgMode = false;
        } else if (mScale.getUnit() == 1) {
            isKgMode = false;
            isgMode = true;
        } else {
            isKgMode = false;
            isgMode = false;
        }

        mViewModel.displayUnit.set(mScale.getStringUnit());
        // 重置扣重
        mScale.pretare(0);

        Runnable timerRun = () -> {
            try {
                if (!isStop) {
                    mScaleHandler.sendEmptyMessage(1);
                }
            } catch (Exception ex) {
                LogUtils.e(ex.getMessage());
            }
        };
        timerThreads.scheduleAtFixedRate(timerRun, 1500, 100, TimeUnit.MILLISECONDS);

//        timerThreads.shutdownNow();

        alarmOpenCommand.put(AlarmState.RED, SerialPortUtil.hexString2Bytes("A1"));
        alarmOpenCommand.put(AlarmState.YELLOW, SerialPortUtil.hexString2Bytes("A2"));
        alarmOpenCommand.put(AlarmState.GREEN, SerialPortUtil.hexString2Bytes("A3"));

        alarmCloseCommand.put(AlarmState.RED, SerialPortUtil.hexString2Bytes("B1"));
        alarmCloseCommand.put(AlarmState.YELLOW, SerialPortUtil.hexString2Bytes("B2"));
        alarmCloseCommand.put(AlarmState.GREEN, SerialPortUtil.hexString2Bytes("B3"));
    }

    private void weightChanged() {
        // 状态栏
        mViewModel.isStable.set(isStable());
        mViewModel.isZero.set(isZero());

        currentWeight = mScale.getFloatNet();
        grossWeight = mScale.getFloatGross();

//        System.out.println("currentWeight====" + currentWeight +"grossWeight===="+ grossWeight);

//            if (isZero()) {
//                mViewModel.displayWeight.set(scalesDecimalPointText);
//            } else
        if (isOL()) {
//                System.out.println("currentWeight====isOL" + isWeightModecurrentWeight + grossWeight);
            mViewModel.displayWeight.set("--OL--");
        } else {
            mViewModel.displayWeight.set(String.format(Locale.getDefault(), scalesDecimalPoint, currentWeight));
        }
        if (currentWeight <= 0) {
            isAddWeight = false;
            isForceRecordStableInt = 0;
            isLoadAutoRecordWeight = 0.0f;
        }
        // 扣重
        mViewModel.displayPreTare.set(String.format(Locale.getDefault(), scalesDecimalPoint, mScale.getFloatTare()));
        // 毛重
        mViewModel.displayGrossWeight.set(isOL() ? "--OL--" : String.format(Locale.getDefault(), scalesDecimalPoint, mScale.getFloatGross()));
        try {
            if (mSerialPortUtilCom != null && isOpencom) {
                byte[] hexString = SerialPortSplice.ByteJoin(mScale.getStringNet(), mScale.getStringUnit());
                if (hexString == null) {
                    return;
                }
                mSerialPortUtilCom.sendBuffer(hexString);
            }
        } catch (Exception e) {

        }


    }


    private void ReadCardMessagePost(ReturnValue result) {
        if (result != null) {
            Message message = Message.obtain();
            message.what = 3;
            String msg;
            Object tag = result.getTag();
            if (tag != null)
                msg = tag.toString();
            else
                msg = "未知错误";
            message.obj = msg;
            mScaleHandler.sendMessage(message);
        }
    }


    public void MenuDialog(View view) {
        beep();
        DialogCheckUser();

    }


//    private void clearProductAttributeSelectView() {
//        mBinding.productSelectItemLayout.clearAllSelectItemView();
//    }

//    private void addOperatorSelectView() {
//        mBinding.productSelectItemLayout.addSelectItemView("操作员", ProductTotalItemLayout.CATEGORY_OPERATOR, true, view -> {
//            Intent intent = new Intent(ScaleActivity.this, SelectItemActivity.class);
//            intent.putExtra(Options.KEY_SELECT_TYPE, SelectType.TYPE_OPERATOR);
//            startActivityForResult(intent, 0x11);
//        });
//    }

//    private void addProductSelectView() {
//        mBinding.productSelectItemLayout.addSelectItemView("产品", ProductTotalItemLayout.CATEGORY_PRODUCT, true, view -> {
//            Intent intent = new Intent(ScaleActivity.this, SelectItemActivity.class);
//            intent.putExtra(Options.KEY_SELECT_TYPE, SelectType.TYPE_PRODUCT);
//            startActivityForResult(intent, 0x11);
//        });
//    }
//    private void addScanSelectView() {
//        mBinding.productSelectItemLayout.addSelectItemView("扫码", ProductTotalItemLayout.CATEGORY_SCAN, true, view -> {
//            Intent intent =new Intent();
//            intent.setClass(ScaleActivity.this,ScanActivity.class);
//            startActivityForResult(intent,0x12);
//        });
//    }

//    private void addDefaultAttributeSelectView(String itemName, String itemCategory, Boolean isRequired) {
//        mBinding.productSelectItemLayout.addSelectItemView(itemName, itemCategory, isRequired, mProductSelectViewClickListener);
//    }

//    private void addDefaultAttributeSelectView() {
//        addProductSelectView();
//        addOperatorSelectView();
////        addScanSelectView();
//        for (int i = 0; i < Converters.sDefaultColumnNames.length; i++) {
//            String defaultColumnName = Converters.sDefaultColumnNames[i];
//            addDefaultAttributeSelectView(defaultColumnName, defaultColumnName, false);
//        }
//    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            // 监听网络变化
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(netWorkStateReceiver, filter);

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            //  getMainUnitDeci
            String prefName = prefs.getString("scales_decimal_point", "3");


            if (prefName.equals("3")) {
                scalesDecimalPoint = "%.3f";
                scalesDecimalPointText = "0.000";
            } else if (prefName.equals("2")) {
                scalesDecimalPoint = "%.2f";
                scalesDecimalPointText = "0.00";
            } else if (prefName.equals("1")) {
                scalesDecimalPoint = "%.1f";
                scalesDecimalPointText = "0.0";
            } else if (prefName.equals("0")) {
                scalesDecimalPoint = "%.0f";
                scalesDecimalPointText = "0";
            } else if (prefName.equals("4")) {
                scalesDecimalPoint = "%.4f";
                scalesDecimalPointText = "0.0000";
            } else if (prefName.equals("5")) {
                scalesDecimalPoint = "%.5f";
                scalesDecimalPointText = "0.00000";
            }
//            else if (prefName.equals("5")&&mScale.getUnit()==0) {
//                scalesDecimalPoint = "%.5f";
//                scalesDecimalPointText = "0.00000";
//            } else if (prefName.equals("4")&&mScale.getUnit()==0) {
//                scalesDecimalPoint = "%.4f";
//                scalesDecimalPointText = "0.0000";
//            }
//            System.out.println("DscalesDecimalPoint===="+scalesDecimalPoint+"scalesDecimalPointText=="+scalesDecimalPointText+mScale.getUnit());
            if (mScale.getUnit() == 0) {

                if (!isKgMode) {
                    DialogRestartApp("称重单位已修改，必须重启才可以正常使用");
                    return;
                }

            } else if (mScale.getUnit() == 1) {

                if (!isgMode) {
                    DialogRestartApp("称重单位已修改，必须重启才可以正常使用");
                    return;
                }
//                scalesDecimalPoint = "%.0f";
//                scalesDecimalPointText = "0";
            } else if (mScale.getUnit() > 1) {
                mScale.setUnit(0);
                DialogRestartApp("该秤当前非克及千克模式,，必须重启，自动切换回kg模式。才可正常使用");
                return;
            }

            mViewModel.displayUnit.set(mScale.getStringUnit());

//            isScalesSwitchServer  =  prefs.getBoolean("scales_switch_server", false);
//            isScalesSwitchServer = prefs.getString("scales_switch_server", "1").equals("1");

//            LogUtils.d("isScalesSwitchServer======="+isScalesSwitchServer);


            mViewModel.showProductPlu.set(PreferenceManager.getDefaultSharedPreferences(this).getString("show_product_plu", "0").equals("1"));

//            mReadCardHelp = CardReadHelp.getSingleton();

            List<Config> deviceCode = dao.get(ConfigKeys.DEVICE_CODE);
            if (deviceCode.size() > 0) {
                deviceCodeStr = deviceCode.get(0).configValue;
            }
            if (deviceCodeStr == null || TextUtils.isEmpty(deviceCodeStr)) {
                showToast("设备码为空,请先去系统设置 -> 基本信息里面里面设置设备编号", TOAST_INFO);
            }
            isShowPrice =  prefs.getString("scales_show_price", "0").equals("1");

            isForceRecord = prefs.getString("scales_force_record", "0").equals("1");
            isForceRecordStable = prefs.getString("scales_force_record_stable", "0").equals("1");
            isLoadAutoRecord = prefs.getString("scales_load_auto", "0").equals("1");

            LogUtils.d("isForceRecordStable==========" + isForceRecordStable);


            if (isForceRecord && isForceRecordStable) {
                showToast("不要同时开启两个自动保存", TOAST_WARNING);
            } else if (isForceRecord && isLoadAutoRecord) {
                showToast("不要同时开启两个自动保存", TOAST_WARNING);
            } else if (isLoadAutoRecord && isForceRecordStable) {
                showToast("不要同时开启两个自动保存", TOAST_WARNING);
            } else if (isForceRecord && isLoadAutoRecord && isForceRecordStable) {
                showToast("不要同时开启三个个自动保存", TOAST_WARNING);
            }


            isOpenPrint = prefs.getBoolean("open_print", false);

            isOpencom = prefs.getBoolean("open_com", true);


            String selectSerialPort = PreferenceManager.getDefaultSharedPreferences(getContext()).getString("alarm_serial_port", "");
//            System.out.println("selectSerialPort===" + selectSerialPort);
            if (!TextUtils.isEmpty(selectSerialPort)) {
                // 打开串口
                try {
                    mSerialPortUtil = new SerialPortUtil(selectSerialPort, 9600);
                } catch (IOException e) {
                    ToastUtils.showLong("继电器控制串口打开失败！");
                }
            }

            String selectComSerialPort = PreferenceManager.getDefaultSharedPreferences(getContext()).getString("alarm_serial_port_com", "");
//            System.out.println("selectComSerialPort===" + selectComSerialPort);

            if (!TextUtils.isEmpty(selectComSerialPort)) {
                // 打开串口
                try {
                    mSerialPortUtilCom = new SerialPortUtil(selectComSerialPort, 9600);
                } catch (IOException e) {
                    ToastUtils.showLong("com串口打开失败！");
                }
            }

            //开启读卡服务
//            readCardMethod();

            isStop = false;

            mViewModel.updateMainCount();

            mBinding.maxRange.setText(String.format("%s %s", mScale.getMainUnitFull(), mScale.getMainUnit() == 0 ? "kg" : "g"));

            mViewModel.querAllMachine();

        } catch (Exception e) {
            showToast("初始化出错" + e.toString(), TOAST_ERROR);

        }

    }


    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(netWorkStateReceiver);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isStop = true;
        mScaleHandler.removeCallbacksAndMessages(null);
        if (mSerialPortUtil != null) {
            changeAlarmState(AlarmState.CLOSE);
            mSerialPortUtil.closeSerialPort();
            mSerialPortUtil = null;
        }
        if (mSerialPortUtilCom != null) {

            mSerialPortUtilCom.closeSerialPort();
            mSerialPortUtilCom = null;
        }


        if (mReadCardHelp != null) {
            mReadCardHelp.cancelReadCard(null);
        }

//        timerThreads.shutdownNow();
//        printThread.shutdownNow();

    }


    /**
     * 用于数据生成前判断、稳定标识的展示与隐藏
     *
     * @return 是否稳定
     */
    private boolean isStable() {
        return mScale.getStabFlag();
    }

    /**
     * 用于零点标识的展示与隐藏
     *
     * @return 是否在零点
     */
    private boolean isZero() {
        return mScale.getZeroFlag();
    }

    /**
     * 用于数据生成前判断
     *
     * @return 是否超量程
     */
    private boolean isOL() {
        return mScale.getStringNet().contains("OL");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        beep();
//        LogUtils.d("keyCode===="+keyCode);
        switch (keyCode) {
            case KeyEvent.KEYCODE_F3:
                shutDown();
                return true;
            case KeyEvent.KEYCODE_BACK:
                closeDialog();
//                if (mReadCardHelp != null) {
//                    mReadCardHelp.cancelReadCard(null);
//                }
                exit();
                return true;

            case KeyEvent.KEYCODE_F1:// 扣重
                if (mScale.getTareFlag()) {
                    mScale.tare();
                } else {
                    boolean result = mScale.pretare(mScale.getFloatNet());
                    if (!result) {
                        showToast("预扣重失败", TOAST_ERROR);
                    }
                }
//                mScale.tare();
//                if (!mScale.tare()) {
//                    showToast("去皮失败");
//                }
                return true;
            case KeyEvent.KEYCODE_F2:// 置零
                if (mScale.zero()) {
//                    cleanTareFloat();
                    lastWeight = 0.000F;
                    currentWeight = 0.000F;
                    grossWeight = 0.000f;
                    lastGrossWeight = 0.000f;

                } else {
                    showToast("置零失败");
                }
                return true;
            case KeyEvent.KEYCODE_MENU:// 桌秤
            case KeyEvent.KEYCODE_MOVE_HOME:// 地秤
                DialogCheckUser();
                return true;
        }

//        if (keyCode == KeyEvent.KEYCODE_F1) {
//            beep();
//            mScale.zero();
////            if (!mScale.tare())
////                ToastUtils.showShort("去皮失败");
//            return true;
//        }
//        if (keyCode == KeyEvent.KEYCODE_F2) {
//            beep();
//            mScale.zero();
//            return true;
//        }
        return super.onKeyDown(keyCode, event);
    }


    private void MenuIntent() {
        Intent intent = new Intent(ScaleActivity.this, MainActivity.class);
        startActivity(intent);
    }


    /**
     * 重置tareFloat
     */
    void cleanTareFloat() {
//        mViewModel.displayPreTare.set(String.format(Locale.getDefault(), scalesDecimalPoint, 0f));
//        mBinding.scaleTareWeight.setText(scalesDecimalPointText);
    }


    /**
     * 关机操作
     */
    public void shutDown() {
        Intent shutDownIntent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
        shutDownIntent.putExtra("android.intent.extra.KEY_CONFIRM", true);
        shutDownIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(shutDownIntent);
    }

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), R.string.tip_press_back, Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int code = event.getKeyCode();
        if (code == KeyEvent.KEYCODE_MENU
                || code == KeyEvent.KEYCODE_MOVE_HOME
                || code == KeyEvent.KEYCODE_BACK
                || (code >= 144 && code <= 153)
                || code == 158 || code == 154 || code == 155 || code == 131 || code == 66 || code == 67 || code == 132 || code == 156 || code == 160 || code == 133 || code == 29 || code == 30 || code == 32
                || code == 112 || code == 19 || code == 20 || code == 21 || code == 22 || code == 23 || code == 33
                || code == 92 || code == 93 || code == 123 || code == 124) {
            return super.dispatchKeyEvent(event);
        } else {
            mGunHelper.analysisKeyEvent(event);
        }
        return true;
    }

    @Override
    public void onScanSuccess(String barcode) {
        if (barcode.isEmpty()) {
            showToast("扫码获取数据为空", TOAST_INFO);
            return;
        }
        ProductDao productDao = AppDatabase.getInstance().productDao();
        List<Product> productList = productDao.getByNumber(barcode);

        if (productList.size() > 0) {
            product = productList.get(0);
//            onProductSelect();

        } else {
            showToast("没有此条码的产品", TOAST_INFO);
        }
    }

    private static class ScaleHandler extends Handler {

        WeakReference<ScaleActivity> mWeakReference;

        ScaleHandler(WeakReference<ScaleActivity> weakReference) {
            this.mWeakReference = weakReference;
        }

        @Override
        public void handleMessage(Message msg) {
            ScaleActivity activity = mWeakReference.get();
            if (activity == null) {
                return;
            }
            if (msg.what == 1) {
                activity.weightChanged();
                activity.forceRecord();
                activity.ForceRecordStable();
                activity.ForceLoadAutoRecordStable();
            }
            if (msg.what == 3) {
//                if (msg.obj.toString().contains("&")) {
//                    activity.showCheckOperator(msg.obj.toString());
//                } else {
//                    activity.PostReCard();
//                }
            }
//            if (msg.what == 4) {
//                activity.intervalRecord();
//            }


        }
    }


    public void ForceRecordStable() {
        if (isStable()) {
//            currentWeight = mScale.getFloatNet();
//            grossWeight = mScale.getFloatGross();
//                if (lastWeight > 0 && currentWeight != lastWeight && isForceRecordStableInt==0) {
            if (lastWeight > 0 && currentWeight > 0) {

                if (isForceRecordStable && isForceRecordStableInt == 0) {

                    saveRecordMethod(currentWeight, grossWeight);
                }
                lastGrossWeight = grossWeight;
                lastWeight = currentWeight;
            }
        }
    }

    public void ForceLoadAutoRecordStable() {
        if (isStable()) {
//            currentWeight = mScale.getFloatNet();
//            grossWeight = mScale.getFloatGross();
//                if (lastWeight > 0 && currentWeight != lastWeight && isForceRecordStableInt==0) {
            if (lastWeight > 0 && currentWeight > 0 && currentWeight > isLoadAutoRecordWeight) {

                if (isLoadAutoRecord) {
                    saveRecordMethod(currentWeight, grossWeight);

                }
                lastGrossWeight = grossWeight;
                lastWeight = currentWeight;
            }
        }
    }


    private void forceRecord() {
        if (isStable()) {
            if (lastWeight > 0 && currentWeight <= threshold * lastWeight) {
/*                // 关闭报警灯
                changeAlarmState(AlarmState.CLOSE);*/
                if (isForceRecord) {
                    saveRecordMethod(lastWeight, lastGrossWeight);

                }

            }
            lastGrossWeight = grossWeight;
            lastWeight = currentWeight;
//            lastWeightStatus = weightStatusStr;

        }
    }


    /**
     * 0 关闭
     * 1 红
     * 2 黄
     * 3 绿
     */
    private AlarmState alarmState = AlarmState.CLOSE;
    private Map<AlarmState, byte[]> alarmOpenCommand = new HashMap<>();
    private Map<AlarmState, byte[]> alarmCloseCommand = new HashMap<>();

    enum AlarmState {CLOSE, RED, YELLOW, GREEN}

    private void changeAlarmState(AlarmState state) {
        if (state == alarmState || mSerialPortUtil == null) return;

        byte[] closeCmd = alarmCloseCommand.get(alarmState);
        if (closeCmd != null) mSerialPortUtil.sendBuffer(closeCmd); // 发送关闭命令

        byte[] openCmd = alarmOpenCommand.get(state);
        if (state != AlarmState.CLOSE && openCmd != null)
            mSerialPortUtil.sendBuffer(openCmd); // 发送开启命令

        alarmState = state;
    }

//    public void showCheckOperator(String cardBean) {
//        mMisc.beep();
////        PostReCard();
//        String[] CardNum = cardBean.split("&");
//        Gson gson = new Gson();
////        final Operator operator = new Operator();
//
//        if (CardNum.length == 3) {
//            ProductDao productDao = AppDatabase.getInstance().productDao();
//            List<Product> productList = productDao.getByProductName(CardNum[2]);
//
//            if (productList.size() > 0) {
//                product = productList.get(0);
//                onProductSelect();
//                CheckOperator(CardNum);
//            } else {
//                CheckProductDialog(productDao, CardNum);
//            }
//
//        } else {
//            CheckOperator(CardNum);
//        }
//
//    }


//    private void CheckProductDialog(ProductDao productDao, String[] cardNum) {
//
//        if (builder01 != null) {
//            return;
//        }
//
//        Product item = new Product();
//        item.groupUUID = Converters.randomUUID();
//        item.groupNumber = null;
//        item.label = null;
//        item.groupName = null;
//        item.number = cardNum[0];
//        item.name = cardNum[2];
//        item.shortHand = Cn2Spell.getPinYinHeadChar(item.name);
//        item.openGroupSetting = false;
//        item.openPreIDSetting = false;
//        item.createTime = System.currentTimeMillis();
//        item.singleWeight = Double.parseDouble("0.000");
//        item.preTare = Double.parseDouble("0.000");
//        item.topLimit = Double.parseDouble("0.000");
//        item.lowLimit = Double.parseDouble("0.000");
//
//
//        builder01 = new AlertDialog.Builder(ScaleActivity.this);
//        builder01.setTitle("产品表无此产品");
//        builder01.setMessage("产品：" + cardNum[2]);
//
//        builder01.setNegativeButton("取消", (dialog, which) -> {
//            builder01 = null;
//            CheckOperator(cardNum);
//        });
//        builder01.setPositiveButton("保存", (dialog, which) -> {
//            builder01 = null;
//            CheckProduct(productDao, item);
//            product = item;
////            onProductSelect();
//            CheckOperator(cardNum);
//        });
//        builder01.show();
//    }

//    private void CheckProduct(ProductDao productDao, Product item) {
//        AppExecutors.getInstance().insertIO()
//                .submit(() -> {
//                    productDao.save(item);
//                    showToast("产品添加成功", TOAST_SUCCESS);
//                });
//    }

//    private void CheckOperator(String[] cardNum) {
//        OperatorDao dao = AppDatabase.getInstance().operatorDao();
//        List<Operator> operatorList = dao.get(cardNum[0]);
//
//        if (operatorList.size() > 0) {
//            operator = operatorList.get(0);
//            mBinding.productSelectItemLayout.setItemViewResult(ProductTotalItemLayout.CATEGORY_OPERATOR,
//                    operator.uuid, operator.name, operator);
//
//        } else {
//
//            if (builder != null) {
//                return;
//            }
//            operator = new Operator();
//            operator.uuid = Converters.randomUUID();
//            operator.name = cardNum[1];
//            operator.cardNumber = cardNum[0];
//
//
//            builder = new AlertDialog.Builder(ScaleActivity.this);
//            builder.setTitle("人员表无此人数据");
//            builder.setMessage("名字：" + cardNum[1] + "\n卡号：" + cardNum[0]);
//
//            builder.setNegativeButton("取消", (dialog, which) -> {
//                builder = null;
//            });
//            builder.setPositiveButton("保存", (dialog, which) -> {
//                builder = null;
//                dao.save(operator);
//                mBinding.productSelectItemLayout.setItemViewResult(ProductTotalItemLayout.CATEGORY_OPERATOR,
//                        operator.uuid, operator.name, operator);
//            });
//            builder.show();
//        }
//    }

//    private void PostReCard() {
//        mScaleHandler.postAtTime(new Runnable() {
//            @Override
//            public void run() {
//                readCardMethod();
//            }
//        }, 3000);
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(timeReceiver);

        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (mReadCardHelp != null) {
            mReadCardHelp.cancelReadCard(null);
        }

//         if (conn != null) {
//            unbindService(conn); // unBindService
//        }
//        unregisterReceiver(mBroadcastReceiver);

    }

    private BroadcastReceiver timeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                mBinding.timer.setText(NumFormatUtil.getFormatDate());
//                if ("00:00".equals(NumFormatUtil.getHHmm())) {
//                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ScaleActivity.this);
//                    String cycle = prefs.getString("scales_auto_export_records_cycle", "none");
//                    if (!"none".equals(cycle)) {
//                        autoExportData(cycle);
//                    }
//                }
            }
        }
    };

    private BroadcastReceiver netWorkStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mBinding.ipAddress.setText(String.format("IP:%s", IPUtil.getLocalIpStr(ScaleActivity.this)));
        }
    };

//    private void autoExportData(String cycle) {
//        Calendar calendar = Calendar.getInstance(Locale.getDefault());
//        calendar.set(Calendar.HOUR_OF_DAY, 0);
//        calendar.set(Calendar.MINUTE, 0);
//        calendar.set(Calendar.SECOND, 0);
//        calendar.set(Calendar.MILLISECOND, 0);
//        String fileName;
//        String fileDir;
//        Date startDate;
//        Date endDate;
//
//        endDate = calendar.getTime(); // 查询条件结束时间
//
//        Calendar temp = Calendar.getInstance();
//        temp.setTime(calendar.getTime());
//
//        if ("day".equals(cycle)) {
//            temp.add(Calendar.DATE, -1);
//            calendar.add(Calendar.DATE, -1); // 数据截至天的日期，向前推一天
//            startDate = temp.getTime();
//            fileName = sdf001.format(startDate) + "_" + sdf001.format(calendar.getTime()) + ".xls";
//            fileDir = sdf001.format(calendar.getTime());
//        } else if ("week".equals(cycle) && calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
//            temp.add(Calendar.DATE, -7);
//            calendar.add(Calendar.DATE, -1); // 数据截至天的日期，向前推一天
//            startDate = temp.getTime();
//            fileName = sdf001.format(startDate) + "_" + sdf001.format(calendar.getTime()) + ".xls";
//            fileDir = sdf001.format(calendar.getTime());
//        } else if ("month".equals(cycle) && calendar.get(Calendar.DAY_OF_MONTH) == 1) {
//            temp.add(Calendar.MONTH, -1);
//            calendar.add(Calendar.DATE, -1); // 数据截至天的日期，向前推一天
//            startDate = temp.getTime();
//            fileName = sdf001.format(startDate) + "_" + sdf001.format(calendar.getTime()) + ".xls";
//            fileDir = sdf001.format(calendar.getTime());
//        } else if ("timeless".equals(cycle)) {
//            temp.setTimeInMillis(0);
//            calendar.add(Calendar.DATE, -1); // 数据截至天的日期，向前推一天
//            startDate = temp.getTime();
//            fileName = "auto_report_timeless.xls";
//            fileDir = "timeless";
//        } else {
//            return;
//        }
//
//        AppExecutors.getInstance().queryIO()
//                .submit(() -> {
//                    try {
//
//                        File tempExcelDir = new File(FileHelp.AUTO_EXCEL_DIR, fileDir);
//
//                        if (!tempExcelDir.exists())
//                            tempExcelDir.mkdirs();
//
//                        File tempExcelFile = new File(tempExcelDir, fileName);
//                        if (tempExcelFile.exists())
//                            tempExcelFile.delete();
//
//                        List<Business> businesses = AppDatabase.getInstance().businessDao()
//                                .getBusinessList(startDate.getTime(), endDate.getTime());
//
//                        BaseDataTable table = new BaseDataTable(fileName,
//                                new ISheetRecord[]{
//                                        new BusinessSheet(businesses)
//                                });
//
//                        ExcelUtils.toExcel(tempExcelDir.getAbsolutePath(), table);
//
//                        if (tempExcelFile.exists()) {
//                            addSharedFile(new SharedFile(tempExcelFile.getAbsolutePath(), fileName));
//                            LLog.debug("auto export Success");
//                        } else {
//                            LLog.error("auto export fail");
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        LLog.error(e.getMessage());
//                    }
//
//                });
//    }


//    @OnMessage(value = Options.MSG_ADD_SHARED_FILE, always = true)
//    public void addSharedFile(SharedFile file) {
//        fileServer.addSharedFile(file);
//    }
//
//    @OnMessage(value = Options.MSG_REMOVE_SHARED_FILE, always = true)
//    public void removeSharedFile(SharedFile file) {
//        fileServer.removeSharedFile(file);
//    }


    public void DialogCheckUser() {

        String passwordStr = PreferenceManager.getDefaultSharedPreferences(ScaleActivity.this).getString("scales_menu_password", "000000");
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.dialog_show_admin, null);
        final EditText editTextName = (EditText) textEntryView.findViewById(R.id.editTextName);
        final EditText editTextNumEditText = (EditText) textEntryView.findViewById(R.id.editTextNum);
        AlertDialog.Builder ad1 = new AlertDialog.Builder(ScaleActivity.this);
        ad1.setTitle("管理员登录:");
        ad1.setView(textEntryView);
        ad1.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int i) {
                String name = editTextName.getText().toString();
                String pass = editTextNumEditText.getText().toString();
                if (name == null || TextUtils.isEmpty(name)) {
                    showToast("请输入名字", TOAST_WARNING);
                    return;
                }
                if (pass == null || TextUtils.isEmpty(pass)) {
                    showToast("请输入密码", TOAST_WARNING);
                    return;
                }
                if (pass.equals(passwordStr)) {
                    MenuIntent();
                } else {
                    showToast("密码错误", TOAST_ERROR);
                }

            }
        });
        ad1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int i) {

            }
        });
        ad1.setCancelable(false);
        ad1.show();// 显示对话框

    }


    private void checckNameBySccan(String scanStr) {
        createLoadingDialog(ScaleActivity.this, "获取客户名称");
//        String byIdGetName = PreferenceManager.getDefaultSharedPreferences(this).getString("scales_post_url_by_id", ByIDGetName);


    }


    public void DialogRestartApp(String showErr) {
        AlertDialog normalDialog =
                new AlertDialog.Builder(ScaleActivity.this)
                        .setTitle("重启App:")
                        .setMessage(showErr)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        try {
//                                            fileServer.stop();
                                            restartApp(ScaleActivity.this);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    }
                                }).create();
        normalDialog.setCanceledOnTouchOutside(false);
        normalDialog.setCancelable(false);
        normalDialog.show();

    }

    public void againGetData() {
        AlertDialog normalDialog =
                new AlertDialog.Builder(ScaleActivity.this)
                        .setTitle("获取数据:")
                        .setMessage("获取最新的数据，会删除原来的数据")
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        beep();
                                        createLoadingDialog(ScaleActivity.this, "数据获取中");
                                        String socketUrl = PreferenceManager.getDefaultSharedPreferences(ScaleActivity.this).getString("scales_post_url_post_base", BaseUrl);
                                        InitCategoryNew.TestInterfaceGetCategory(socketUrl, deviceCodeStr);
                                    }
                                })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int i) {

                            }
                        }).create();
        normalDialog.setCanceledOnTouchOutside(false);
        normalDialog.setCancelable(false);
        normalDialog.show();

    }

    /**
     * 重启app
     *
     * @param context
     */
    public static void restartApp(Context context) {
        Intent intent = context.getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName());
        PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
        System.exit(0);
    }


    @OnMessage(value = Options.MSG_POST_SUCCESS, always = true)
    public void showPostSuccess(EventBusMessage msg) {
        mViewModel.updateMainCount();
    }


    @OnMessage(value = Options.MSG_CONNECT_SUCCESS_TEST, always = true)
    public void ConnectSuccess(EventBusMessage msg) {
        closeDialog();
        if (msg.getSuccess() == 1) {

//            DeleteCategory();

            mScaleHandler.postAtTime(new Runnable() {
                @Override
                public void run() {
                    createLoadingDialog(ScaleActivity.this, "数据获取中");
                    String socketUrl = PreferenceManager.getDefaultSharedPreferences(ScaleActivity.this).getString("scales_post_url_post_base", BaseUrl);
                    InitCategoryNew.getCategoryData(socketUrl, deviceCodeStr);
                }
            }, 200);


        } else {
            ShowPlu();
            showToast(msg.getDes(), TOAST_ERROR);
        }

    }




    @OnMessage(value = Options.MSG_POST_SHOW, always = true)
    public void showGetData(EventBusMessage msg) {
        closeDialog();
        if (msg.getSuccess() == 1) {
            ShowPlu();
            showToast(msg.getDes(), TOAST_SUCCESS);
        } else {
            showToast(msg.getDes(), TOAST_ERROR);
        }

    }


    /**
     * 获取设备ID，GSM手机为IMEI、CDMA手机为MEID
     *
     * @return
     */
    public String getDeviceId() {
        return Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
    }


}